package com.tushen.task;

import com.tushen.utils.SqlSessionFactoryUtil;
import com.tushen.utils.Utils;
import java.io.*;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 精细三维流场处理
 *  1.获取 lon.csv,lat.csv,u.csv,v.csv
 *  2.解析文件入库至uv_shp_result_版本号
 *  3.创建索引
 * @author likun
 * @version 1.0
 * @date 2020/12/13 7:27 上午
 */
public class UV3 {
    public static void main(String[] args){
        if(args.length<2){
            System.out.println("plese input filePah and version");
            return;
        }
        String dir=args[0];
        String version=args[1];
        processUV(dir,version);
    }

   public static void processUV(String dir,String version){
       SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMddHH");
       Date dt=null;
       int startIndex=dir.lastIndexOf("\\")+1;
       if(startIndex==0){
           startIndex=dir.lastIndexOf("/")+1;
       }
       String dtmstr=dir.substring(startIndex);
       try {
           dt=  simpleDateFormat.parse(dtmstr);
       }catch (Exception e){
           e.printStackTrace();
           System.out.println("文件路径中时间格式不对，需要yyyyMMddHH格式");
           return;
       }
       String fileSep=java.io.File.separator;
       String pathU=dir+fileSep+"u.csv";
       String pathV=dir+fileSep+"v.csv";
       Calendar calendar=Calendar.getInstance();
       calendar.setTime(dt);

       //处理dye浓度数据
       // prcossDyePoint(calendar,pathLont,pathLat,pathDye,dstDir);
       String tableName="uv_shp_result_"+version;
       String outPath="D:/tmp/"+tableName+".csv";
//       String outPath="/Users/likun/Downloads/tmp/"+tableName+".csv";
       //读取uv数据，并生成三角网shp
       prcossUVTriangle(calendar,tableName,pathU,pathV,outPath);
   }

    // 创建数据表
    private static void createTable(String tableName){
        String sql="DROP TABLE IF EXISTS "+tableName+";" +
                "CREATE TABLE "+tableName+" ("+
                "  dt date NOT NULL," +
                "  tm time(0) NOT NULL," +
                "  layer int2 NOT NULL," +
                "  id int4 NOT NULL," +
                "  u numeric(10,6)," +
                "  v numeric(10,6)" +
                ");";
        SqlSessionFactoryUtil.excuteUpdateSql(sql);
        System.out.println(tableName+" created;");
    }

    // 创建数据表索引
    private static void createTableIndex(String tableName){
        String sql="CREATE INDEX "+tableName+"_dtm_idx ON "+tableName+" USING btree (" +
                "  dt pg_catalog.date_ops ASC NULLS LAST," +
                "  tm pg_catalog.time_ops ASC NULLS LAST," +
                "  layer pg_catalog.int2_ops ASC NULLS LAST);";
        SqlSessionFactoryUtil.excuteUpdateSql(sql);
        System.out.println(tableName+" index created;");

    }

    //读取uv数据
    private static void prcossUVTriangle(Calendar calendar,String tableName,String pathU,String pathV,String outPath){
        try {
            File outFile=new File(outPath);
            if (outFile.exists()){
                outFile.delete();
            }
            createTable(tableName);
            long start=System.currentTimeMillis();
            File fileU = new File(pathU);
            File fileV = new File(pathV);
            String encoding = "UTF-8";
            if (fileU.isFile() && fileU.exists()&&fileV.isFile() && fileV.exists()) {

                InputStreamReader readU = new InputStreamReader(
                        new FileInputStream(fileU), encoding);
                InputStreamReader readV = new InputStreamReader(
                        new FileInputStream(fileV), encoding);
                BufferedReader bufferedReaderU = new BufferedReader(readU);
                BufferedReader bufferedReaderV = new BufferedReader(readV);
                String lineTxtU = "";
                String lineTxtV = "";
                int layer=1;
                int tm=1;
                while ((lineTxtU = bufferedReaderU.readLine()) != null&&(lineTxtV = bufferedReaderV.readLine()) != null) {
                    if(lineTxtU.length()==0){
                        layer=1;
                        tm++;
                        calendar.add(Calendar.HOUR,1);
                        System.out.println("时刻:"+tm);
                        dumpUVData(tableName,outPath);
                        outFile.delete();
                        continue;
                    }
                    String[] myArrayU=lineTxtU.trim().split(",");
                    String[] myArrayV=lineTxtV.trim().split(",");
                    List<Double> lineListU = new ArrayList<Double>();
                    List<Double> lineListV = new ArrayList<Double>();
                    for (String str : myArrayU) {
                        lineListU.add(Double.parseDouble(str));
                    }
                    for (String str : myArrayV) {
                        lineListV.add(Double.parseDouble(str));
                    }
                    writeData2File(calendar,layer,lineListU,lineListV,outPath);
                    layer++;
                }
                readU.close();
                readV.close();
            } else {
                System.out.println("文件不存在!");
            }


            long end=System.currentTimeMillis();
            dumpUVData(tableName,outPath);//入库
            outFile.delete();
            long end2=System.currentTimeMillis();
            double div=(end2-end)/1000.0;
            System.out.println("最后一次写入到文件耗时:"+div+"秒");

            createTableIndex(tableName);//添加索引
            long end3=System.currentTimeMillis();
            div=(end3-end2)/1000.0;
            System.out.println("创建索引耗时:"+div+"秒");
            div=( System.currentTimeMillis()-start)/1000.0;
            System.out.println("总耗时:"+div+"秒");


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void writeData2File(Calendar calendar,int layer,List<Double> lineListU,List<Double> lineListV,String outFilePath){
        java.sql.Date dt=new java.sql.Date(calendar.getTime().getTime());
        Time tm=new java.sql.Time(calendar.getTime().getTime());
        try {
            FileWriter fileWriter = new FileWriter(outFilePath, true);
            for (int i = 0; i < lineListU.size(); i++) {
                double u = lineListU.get(i);
                double v = lineListV.get(i);
                double direction = Utils.getDirection(u, v);
                double speed = Math.sqrt(u * u + v * v);
                StringBuilder sb = new StringBuilder(dt + ",");
                sb.append(tm + ",");
                sb.append(layer + ",");
                sb.append(i + ",");
                sb.append(direction + ",");
                sb.append(speed);
                sb.append(System.lineSeparator());
                fileWriter.write(sb.toString());
            }
            fileWriter.flush();
            fileWriter.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    //将uv结果入到数据库
    private static void dumpUVData(String tableName,String outFilePath){
        String sql="copy "+tableName+" from '"+outFilePath+"'  DELIMITER ',' csv header";
        System.out.println("执行入库:"+sql);
        SqlSessionFactoryUtil.excuteUpdateSql(sql);
        System.out.println("入库完成");
    }


}
